<template>
  <div>
    <div class="center-pane" :class="isWide ? 'wide' : ''">
      <el-row>
        <el-col :span="viewSpan.left">
          <mat-detail
            :mat="mat"
            @select="select"
            @click-title="onTitle"
          ></mat-detail>
        </el-col>
        <el-col :span="viewSpan.right">
          <view-notes :context="context"></view-notes>
          <!--
          <div class="notes-pane">
            <div class="title-bar">
              <span class="title"> 笔记 </span>
              <span class="right">
                <el-popover
                  placement="left-start"
                  width="200"
                  trigger="click"
                >
                  <el-button slot="reference">激活</el-button> 
                  <ri i="add" slot="reference"></ri>
                  <div class="menu-selector">
                    <div class="menu-item" v-for="(s, i) in sections" :key="i">
                      {{s}}
                    </div>
                  </div>
                </el-popover>
              </span>
            </div>
            <scroller height="80vh">
              <notes
                :context="context"
                @notes-loaded="notesLoaded"
                @update-context="onUpdateContext"
              ></notes>
            </scroller>
          </div>
          -->
        </el-col>
      </el-row>
    </div>
    <inline-notes :mat="mat"></inline-notes>
  </div>
</template>

<script>
import { NoteKind, NoteScope, MatKind, MatFormat } from "@js/constants.js";
import MatDetail from "./MatDetail.vue";
// import Notes from "../notes/Notes.vue";
import ViewNotes from "./ViewNotes.vue";
import InlineNotes from "./InlineNotes.vue";
import paths from "@js/utils/paths.js";

export default {
  components: {
    MatDetail,
    ViewNotes,
    // Notes,
    InlineNotes,
  },
  data() {
    return {
      isShowHidden: false,
      id: this.$route.params.mid,
      mat: {
        title: "",
        content: "",
      },
      myNotes: [],
      star: {},
      context: this.dftContext(),
      selectedText: "",
      activeStep: 0,
      showClock: false,
      writeTimeLimit: 30, // TODO: 这个数值应当根据内容长短而有所变化
      isLarge: false,
      sections: ["a", "b", "c"],
    };
  },
  created() {
    this.initData();
    console.log("params: ", JSON.stringify(this.$route.params));
  },
  watch: {
    $route() {
      this.initData();
    },
  },
  computed: {
    isWide() {
      let wideKinds = [
        MatKind.File,
        MatKind.Dir,
        MatKind.Project,
        MatKind.Chapter,
      ];
      if (wideKinds.includes(this.mat.kind)) {
        return true;
      } else {
        return false;
      }
    },
    viewSpan() {
      if (this.isWide) {
        return { left: 14, right: 10 };
      } else {
        return { left: 12, right: 12 };
      }
    },
    codeLang() {
      if (this.mat.title) {
        let t = this.mat.title.split(".");
        return "lang-" + t[t.length - 1];
      } else {
        return "";
      }
    },

    matLink() {
      let link = this.mat.link;
      if (!link) {
        console.log(this.mat.source, this.mat.title);
        let p = this.$route.path.replace("/projects/", "");
        link = "https://" + p;
      }
      return link;
    },
  },
  methods: {
    initData() {
      this.context = this.dftContext();
      this.mat.content = "";
      // 获取诗歌内容
      let id = this.$route.params.mid;
      console.log("router:", this.$route);
      if (id) {
        this.id = id;
        this.$axios
          .get("/api/v1/mats/get/" + this.id)
          .then((res) => {
            let mat = res.data;
            if (mat.kind == MatKind.Poem) {
              this.isLarge = true;
            }
            this.mat = mat;
            this.context.mat = mat;
            this.context.content = mat.title;
            // this.loadMyNotes();
          })
          .catch((e) => console.log(e));
      } else {
        if (this.$route.meta.isdir) {
          this.mat.format = MatFormat.Dir;
        } else {
          this.mat.format = MatFormat.Text;
        }
        // 为每句话注册响应事件
        let params = this.$route.params;
        let p = paths.join(
          "/" + params.source,
          params.organization,
          params.project,
          params.nodetype,
          params.version,
          params.pathMatch
        );
        let fullpath = this.$route.path;
        console.log("file path:", p);
        console.log("full path:", fullpath);
        this.$axios
          .get("/api/v1/mats/getbypath/" + p)
          .then((res) => {
            let mat = res.data;
            console.log("mat:", mat);
            this.mat = res.data;
            if (mat.id) {
              this.context.mat = this.mat;
              this.context.content = this.mat.title;
              // this.loadMyNotes();
              this.id = mat.id;
            } else {
              // this.mat.title = "/" + p;
              this.context.mat = this.mat;
              this.context.content = this.mat.title;
            }
            console.log(this.mat);
          })
          .catch((e) => console.log(e));
      }
    },
    addStar() {
      var json = {
        scope: NoteScope.Article,
        mid: Number(this.id),
        value: 1,
      };
      return this.authPost("/api/v1/star/add", json).then((res) => {
        let star = res.data;
        this.star = star;
        this.showClock = false;
      });
    },
    handleClose() {
      this.showClock = false;
    },
    showWrite() {
      if (this.$refs.writeclock) {
        this.$refs.writeclock.reset();
      }
      this.showClock = true;
    },
    onUpdateContext(data) {
      Object.assign(this.context, data);
    },
    dftContext() {
      return {
        kind: NoteKind.Note,
        scope: NoteScope.Article,
        line: 0,
        title: this.mat ? this.mat.title : "",
        content: "",
        mat: this.mat || {},
      };
    },
    onTitle() {
      this.context = this.dftContext();
      this.selectedText = "";
      this.clearCurrentSelection();
    },
    select(data) {
      //Object.assign(this.selection, data);
      this.context.el = data.el;
      this.context.content = data.content;
      this.context.event = data.event;
      this.context.line = data.line;
      this.context.scope = data.scope;
      this.context.s = data.s;
      this.context.e = data.e;

      this.selectedText = data.content;
      this.highlightSelection(this.context);
    },
    // 取消其他句子的高亮，并将当前句子高亮
    highlightSelection(sel) {
      this.clearCurrentSelection();
      if (sel.type == "line") {
        let sent = sel.el;
        sent.classList.add("selected");
      } else if (sel.type == "word") {
        let spos = sel.location.startpos;
        let epos = sel.location.endpos;
        let sent = sel.el;
        // 找到所有涉及到的span
        let curIdx = 0;
        for (let span of sent.children) {
          let text = span.textContent;
          let textLen = text.length;
          if (curIdx >= spos && curIdx + textLen <= epos) {
            span.classList.add("selected");
          }
          curIdx += text.length;
        }
        console.log("selected location:", JSON.stringify(sel.location));
        //this.highlightWord(sent, spos, epos);
      }
    },
    clearCurrentSelection() {
      // 清除所有包含selected类别的span
      let highlighted = this.$el.getElementsByClassName("selected");
      Array.from(highlighted).forEach((span) =>
        span.classList.remove("selected")
      );
    },
    notesLoaded(notes) {
      /*
      // 整首诗的标星
      for (let star of notes.filter(
        (n) => n.scope == NoteScope.Article && n.kind == NoteKind.Star
      )) {
        console.log("star:", JSON.stringify(star));
        this.star = star;
      }
      // 标星的行
      let linestars = notes.filter((n) => n.scope == NoteScope.Line);
      linestars.sort((a, b) => a.line - b.line);
      if (linestars.length) this.markLines(linestars);
      */
      // 添加注音
      let wordNotes = notes.filter(
        (n) => n.s.scope == NoteScope.Word || n.s.scope == NoteScope.Char
      );
      if (wordNotes.length) this.markWords(wordNotes);
    },
    markLines(linestars) {
      let lineSpans = this.$el.getElementsByClassName("line");
      if (lineSpans.length == 0) {
        lineSpans = this.$el.getElementsByClassName("code-line");
      }
      for (let lineSpan of lineSpans) {
        let linenum = Number(lineSpan.getAttribute("linenum"));
        // TODO: 将遍历数组改为查询map以提升性能
        for (let star of linestars) {
          if (linenum == star.line) {
            lineSpan.classList.add("mark");
          }
        }
      }
    },
    updateStats(notes) {
      let sentCounts = {};
      notes.map((n) => {
        if (n.ptype == 1) {
          let sentid = n.sentid;
          if (sentid in sentCounts) {
            sentCounts[sentid]++;
          } else {
            sentCounts[sentid] = 1;
          }
        }
      });
      let sents = this.$el.getElementsByClassName("sent");
      for (let sent of sents) {
        let sentid = sent.id;
        if (sentid in sentCounts) {
          let stat = sent.nextSibling;
          stat.innerText = sentCounts[sentid];
          stat.style.display = "inline";
        }
      }
    },
  },
};
</script>

<style lang="stylus">
.go-back
  position absolute
  font-weight bold
  cursor pointer
  color #333
  border 1px solid #eee
  border-radius 5px
  padding 10px
  left 90px

.center-pane
  text-align left

  .mat-pane
    text-align left
    width 100%
    padding 1vh 0

    .mat-title-pane
      padding 0.5vh 0
      border-bottom 1px solid #eee

      .mat-title
        padding 0.5vh 0.5vw 0.5vh 0
        width 100%
        cursor pointer

        &.poem
          font-weight bold
          font-size 1.5em

        .mat-fav
          margin-right 8px

        span.author
          font-weight normal
          color #666

        a.mat-link
          font-size 1.2em
          cursor pointer
          margin-right 10px

        a.mat-link:hover
          color #409EFF

      .mat-stats
        color #409EFF

      .mat-toolbar
        float right
        margin-right 10px

    .mat-status
      min-height 30px

      & div
        float right
        text-align center

    .mat-content
      font-size 1.2em
      min-height 100px
      max-height 400px

      .line
        width auto
        cursor pointer

        &:hover
          background-color #ECF5FF

    border-right 1px solid #eee

  .notes-pane
    padding 0px 10px 0px 30px
    text-align left

  .mat-toolbar
    font-weight normal
    font-size 1.2em

    a
      color black

    span
      margin-left 10px

    svg
      color #409eff
      cursor pointer
      margin-left 10px
</style>